package com.shawn.autoconfig.template;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.shawn.autoconfig.properties.OssProperties;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class OssTemplate {

    private OssProperties ossProperties;

    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    /**
     * 了加载
     *
     * @param fileName 文件名称
     * @param is       输入流
     * @return {@link String} 访问路径url
     */
    public String upLoading(String fileName, InputStream is) {
        //获取oss关键参数
        String endpoint = ossProperties.getEndpoint();
        String bucketName = ossProperties.getBucketName();
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        String url = ossProperties.getUrl();
        //        构建OssClient关键对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //设定存储路径 日期文件夹+UUID+文件名后缀
            String storePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));

            //创建PutObject请求
            ossClient.putObject(bucketName, storePath, is);
            //返回访问路径
            return url + storePath;
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
